"""
Python 互斥锁解决多线程资源竞争问题
"""
import time
import threading


# 线程共享变量
g_num = 0


# 创建一个互斥锁
# 默认是未上锁的状态
mutex = threading.Lock()


def work1(num):
    global g_num
    for i in range(num):
        mutex.acquire()  # 上锁
        g_num += 1
        mutex.release()  # 解锁

    print("---work1---g_num=%d" % g_num)


def work2(num):
    global g_num
    for i in range(num):
        mutex.acquire()  # 上锁
        g_num += 1
        mutex.release()  # 解锁

    print("---work2---g_num=%d" % g_num)


def mutex_test():
    """互斥锁测试"""

    # 创建2个线程，让他们各自对g_num加1000000次
    count = 1000000
    
    t1 = threading.Thread(target=work1, args=(count,))
    t1.start()

    t2 = threading.Thread(target=work2, args=(count,))
    t2.start()

    # 等待计算完成
    # len(threading.enumerate()) = 当前程序线程的数量
    # 为1说明只剩下主线程
    while len(threading.enumerate()) != 1:
        time.sleep(1)

    print("2个线程对同一个全局变量操作之后的最终结果是:%s" % g_num)


def main():
    mutex_test()


if __name__ == '__main__':
    main()